﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using HIHS.BaseLib.Basics;
using HIHS.Logic.App;
using HIHS.Logic.User;
using HIHS.Forms.IM;
using HIHS.Entity.IM;
using System.Diagnostics;
using HIHS.NetEntity.IM;
using HIHS.Logic.IM;
using System.Threading.Tasks;
using HIHS.BaseLib;



namespace HIHS.Form.Main
{
    public partial class TopBar : BaseFunctionControl
    {
        ImAttachMsgLogic attachMsgLogic = new ImAttachMsgLogic();
        AppResource resource = (AppResource)HIHSApplication.Resource;
        public TopBar()
        {
            InitializeComponent();
        }

        private void btnUserInfo_Click(object sender, EventArgs e)
        {
            var fm = new FmUserInfo();
            fm.ShowDialog();
        }

        private void TopBar_Load(object sender, EventArgs e)
        {

            btnUserInfo.Text = resource.LoginUserInfo.UserNameCn;
            //int length=System.Text.UTF8Encoding.UTF8.GetBytes(resource.LoginUserInfo.UserNameCn).Length;
            if (btnUserInfo.Text.Length > 3)
                btnUserInfo.Text = resource.LoginUserInfo.UserNameCn.Substring(0, 3);
            UpdateMessageIcon();
            ReloadData(true);
            //FunctionEntity fe = new FunctionEntity { Control=this, FunctionType= FunctionType.Control  };

        }

        public override void ReloadData(object data)
        {
            panelMyApp.Controls.Clear();
            if (AppResource.CurrentResource.UserConfig.MyApps != null && AppResource.CurrentResource.UserConfig.MyApps.Count > 0)
            {
                //var list = HIHSApplication.AppFunMunes.Where(o => AppResource.CurrentResource.UserConfig.MyApps.Any(mc => o.AppId == mc)).ToList();
                List<FunctionEntity> list = new List<FunctionEntity>();
                foreach (var item in AppResource.CurrentResource.UserConfig.MyApps)
                {
                    FunctionEntity fe = HIHSApplication.AppFunMunes.FirstOrDefault(o => o.AppCode == item);
                    if (fe != null)
                        list.Add(fe);
                }

                if (list.Count == 0)
                    return;
                if ((bool)data)
                    HIHSApplication.MainForm.OpenMenu();


                int buffonWidth = 110;
                bool displayTest = true;
                if (list.Count() * buffonWidth >= panelMyApp.Width)
                    buffonWidth = 40;
                list.Reverse();
                foreach (FunctionEntity item in list)
                {
                    SimpleButton button = new SimpleButton();
                    button.AllowFocus = false;
                    button.Appearance.BackColor = System.Drawing.Color.Transparent;
                    button.Appearance.Options.UseBackColor = true;
                    button.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.UltraFlat;
                    button.Dock = System.Windows.Forms.DockStyle.Left;
                    if (item.Image != null)
                        button.Image = item.Image.GetThumbnailImage(32, 32, null, System.IntPtr.Zero);
                    button.Size = new System.Drawing.Size(buffonWidth, 40);
                    if (displayTest)
                        button.Text = item.Title;
                    button.ToolTip = item.Title;
                    button.Click += (o, e) => HIHSApplication.MainForm.App_Click(item);
                    panelMyApp.Controls.Add(button);
                }
                //打开我的应用的第一个应用做为主页
                if ((bool)data)
                    HIHSApplication.MainForm.App_Click(list.Last());
            }
            else
            {
                if ((bool)data)
                    HIHSApplication.MainForm.OpenMenu();
            }
        }

        /// <summary>
        /// 更新消息图标
        /// by ZhaoHuan
        /// </summary>
        public void UpdateMessageIcon()
        {
            new Task(() =>
            {
                if (this.btnMsg.InvokeRequired)//如果调用控件的线程和创建创建控件的线程不是同一个则为True
                {
                    while (!this.btnMsg.IsHandleCreated)
                    {
                        //解决窗体关闭时出现“访问已释放句柄“的异常
                        if (this.btnMsg.Disposing || this.btnMsg.IsDisposed)
                            return;
                    }
                    this.btnMsg.Invoke(new Action(() =>
                    {
                        SetMessageIcon();
                    }));
                }
                else
                {
                    SetMessageIcon();
                }

            }).Start();

        }

        /// <summary>
        /// 设置消息图标
        /// by ZhaoHuan
        /// </summary>
        private void SetMessageIcon()
        {
            GetAttachMsgRequest getAttachMsgRequestparam = new NetEntity.IM.GetAttachMsgRequest();
            getAttachMsgRequestparam.criteria = new GetAttachMsgRequestCriteria();
            getAttachMsgRequestparam.criteria.toAccids = resource.UserInfo.userInfo.userId.ToString();
            getAttachMsgRequestparam.criteria.isRead = 0;
            getAttachMsgRequestparam.criteria.pageSize = 1;
            getAttachMsgRequestparam.criteria.pageIndex = 1;

            var pageList = attachMsgLogic.GetAttachMsgList(getAttachMsgRequestparam);
            if (pageList != null && pageList.result != null && pageList.result.Count() > 0)
                //有未读消息
                btnMsg.Image = global::HIHS.Form.Main.Properties.Resources.消息提醒有红点;
            else
                btnMsg.Image = global::HIHS.Form.Main.Properties.Resources.消息提醒;
        }

        /// <summary>
        /// 设置
        /// by ZhaoHuan
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnSetting_Click(object sender, EventArgs e)
        {
            FmSetting fmSetting = new FmSetting();
            fmSetting.ShowDialog();

        }

        private void btnCache_Click(object sender, EventArgs e)
        {

            //            #region 打开测试窗口
            //#if CX
            //            FmZhT from = new FmZhT();
            //            from.Show();
            //#endif
            //            #endregion

            try
            {
                UserLogic.GetProductTask().Start();
            }
            catch
            {
                throw new Exception("获取产品缓存失败！");
            }
            if (HIHSApplication.MainForm.OpenedFe.Count > 0)
                foreach (FunctionEntity item in HIHSApplication.MainForm.OpenedFe)
                    if (item.ClassInfo != null && item.ClassInfo.ClassFillName == "HIHS.Winform.Controls.WebUserControl.WebMainControl")
                        HIHSApplication.MainForm.Msg(item);
        }

        private void btnTest_Click(object sender, EventArgs e)
        {

        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            var loginUser = ((AppResource)HIHSApplication.Resource).LoginUserInfo;
            var userInfo = ((AppResource)HIHSApplication.Resource).UserInfo;
            string str = "http://help.cexingpet.com/client/?provider_id=11418&uid=m1QRWkv0pp7XoE7mqVfJ4Qz0rzoTHLBk&name=测试&mobilePhone={1}&ticket_customField_132843={2}&ticket_customField_129913={3}";
            // 第一个参数备用
            str = string.Format(str, new string[] {
                loginUser.UserNameCn,
                userInfo.userInfo.MobileOfNoCode,
                loginUser.CurrentOrg.clinicName,
                loginUser.CurrentOrg.systemId.ToString() });
            Process.Start(str);
        }

        UcMessagePanel ump;
        private void btnMsg_Click(object sender, EventArgs e)
        {
            if (ump == null)
            {
                ump = new UcMessagePanel();
                ump.Window.Location = btnMsg.PointToScreen(new Point(-((ump.Width + 40) / 2), btnMsg.Height));
                ump.Window.FormClosed += (s, e1) => { ump = null; };
                ump.Show();
            }
            else
            {
                ump.Window.Close();
            }
        }
    }
}
